package com.dyc.course.sys.controller;

import com.dyc.course.common.annotation.SysLog;
import com.dyc.course.common.utils.R;
import com.dyc.course.sys.entity.SysConfigEntity;
import com.dyc.course.sys.repository.SysConfigRepository;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

import javax.validation.Valid;

/**
 * 系统配置信息
 *
 */
@RestController
@RequestMapping("/sys/config")
public class SysConfigController extends AbstractController {
	
	@Autowired
	private SysConfigRepository repository;
	
	/**
	 * 所有配置列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:config:list")
	public R list(@RequestParam Map<String, Object> params) {
		String page = (String) params.get("page");
		String size = (String) params.getOrDefault("limit", "10");
		String sortBy = (String) params.getOrDefault("sortBy", "id");
		Sort sort = Sort.by(sortBy);
		PageRequest pageRequest = PageRequest.of(Integer.parseInt(page)-1, Integer.parseInt(size), sort);
		Page<SysConfigEntity> entities;
		if (params.containsKey("paramKey") && params.get("paramKey").toString().length() > 0) {
			entities = repository.findByParamKeyLike("%" + (String) params.get("paramKey") + "%", pageRequest);
		} else {
			entities = repository.findAll(pageRequest);
		}
		return R.ok().put("page", entities);
	}
	
	/**
	 * 配置信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("sys:config:info")
	@ResponseBody
	public R info(@PathVariable("id") Long id) {
		Optional<SysConfigEntity> optional = repository.findById(id);
		SysConfigEntity config = null;
		if (optional.isPresent()) {
			config = repository.getOne(id);
		}
		return R.ok().put("config", config);
	}
	
	/**
	 * 保存配置
	 */
	@SysLog("保存配置")
	@RequestMapping("/save")
	@RequiresPermissions("sys:config:save")
	public R save(@RequestBody @Valid SysConfigEntity entity) {
		repository.save(entity);
		return R.ok();
	}
	
	/**
	 * 修改配置
	 */
	@SysLog("修改配置")
	@RequestMapping("/update")
	@RequiresPermissions("sys:config:update")
	public R update(@RequestBody SysConfigEntity entity){
		repository.save(entity);
		return R.ok();
	}
	
	/**
	 * 删除配置
	 */
	@SysLog("删除配置")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:config:delete")
	public R delete(@RequestBody Long[] ids) {
		for (Long id : ids) {
			repository.deleteById(id);
		}
		return R.ok();
	}

}
